package com.exampl.health.util;

import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

/**
 * 文件上传工具类
 */
public class FileUploadUtil {

    private static final long MAX_FILE_SIZE = 2 * 1024 * 1024; // 2MB
    private static final String[] ALLOWED_EXTENSIONS = {"jpg", "jpeg", "png", "gif"};

    /**
     * 上传头像
     */
    public static String uploadAvatar(MultipartFile file, HttpServletRequest request) throws IOException {
        // 验证文件大小
        if (file.getSize() > MAX_FILE_SIZE) {
            throw new IOException("文件大小不能超过2MB");
        }

        // 验证文件类型
        String originalFilename = file.getOriginalFilename();
        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf(".") + 1).toLowerCase();
        boolean allowed = false;
        for (String ext : ALLOWED_EXTENSIONS) {
            if (ext.equals(fileExtension)) {
                allowed = true;
                break;
            }
        }
        if (!allowed) {
            throw new IOException("只支持JPG, JPEG, PNG, GIF格式的图片");
        }

        // 生成新的文件名
        String newFileName = UUID.randomUUID().toString() + "." + fileExtension;

        // 创建保存目录
        String uploadDir = request.getServletContext().getRealPath("/uploads/avatar/");
        File dir = new File(uploadDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        // 保存文件
        Path filePath = Paths.get(uploadDir, newFileName);
        Files.write(filePath, file.getBytes());

        return "/uploads/avatar/" + newFileName;
    }
}
